package com.rtwo.shiro.controller;

import com.rtwo.shiro.entity.ShUser;
import com.rtwo.shiro.service.ShUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by hasee on 2017/6/14.
 */
@Controller
@RequestMapping("/shiro")
public class ShiroController {

    @Autowired
    private ShUserService userService;

    @RequestMapping("/")
    public String toLogin(){
        System.out.println("login");
        return "login";
    }

    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response){
        ModelAndView modelAndView = new ModelAndView();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        ShUser user = userService.findUserByUsername(username);
        if(user==null){
            request.setAttribute("msg","用户名不存在");
            modelAndView.setViewName("/toLogin");
            return modelAndView;
        }
        if (!user.getPassword().equals(password)) {
            modelAndView.setViewName("toLogin");
            request.setAttribute("msg", "账号密码错误");
            return modelAndView;
        }
        SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject());
        // 登录后存放进shiro token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        // 登录成功后会跳转到successUrl配置的链接，不用管下面返回的链接。
        modelAndView.setViewName("/home");
        return modelAndView;
    }

    @RequestMapping("/home")
    public String home() {
        System.out.println("登录成功");
        return "home";
    }

}
